package com.etc.util;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.etc.entity.Contents;
import com.etc.service.ContentsService;
import com.etc.service.FileService;

@Component
public class TestCopyFiles2 {

	@Autowired
	private ContentsService contentsService;
	@Autowired
	private FileService fileService;
	@Autowired
	private CopyDocuments copyDocuments;

	Integer a = 1;

	public void CopyFiles(Integer userId, Integer fromsecondId, Integer tosecondId, String name) throws Exception {

		Integer tokey = null;
		if (a == 1) {
			// 根据contentsId查找目录对象
			Contents contents2 = contentsService.selectByPrimaryKey(fromsecondId);

			// 设置目录对象的上一级目录id
			contents2.setSecondid(tosecondId);

			contents2.setContentsid(null);

			String path2 = contentsService.getContentsPathById(2);

			contents2.setContentspath(path2 + "\\" + contents2.getContentsname());

			contentsService.insertSelectiveGetKey(contents2);

			tokey = contents2.getContentsid();

			a++;
		}

		// 根据secondId查询所有的子目录
		List<Contents> contentsList = contentsService.getContentsBySecondId(fromsecondId, userId);
		// 根据父目录id查询在该目录下的所有文件
		List<com.etc.entity.Files> fileList = fileService.getFileBySecondId(fromsecondId, userId);

		if (contentsList != null) {
			// 遍历目录
			for (Contents contents : contentsList) {
				// 获取目录的secondId(这个就是上面的fromsecondId)
				Integer secondId = contents.getSecondid();

				if (tokey == null) {
					tokey = tosecondId;
				}
				// 获取目标路径
				String path = contentsService.getContentsPathById(tokey);
				// 改变路径 添加数据
				contents.setContentspath(path + "\\" + contents.getContentsname());
				// 当前子目录id
				Integer fromId = contentsService.selectBySecondIdAndContentsName(secondId, contents.getContentsname())
						.getContentsid();
				contents.setContentsid(null);
				// 设置上一级目录id
				contents.setSecondid(tokey);
				// 添加数据获取主键值
				int key = contentsService.insertSelectiveGetKey(contents);

				// 递归调用
				CopyFiles(userId, fromId, key, contents.getContentsname());

			}
		}

		if (fileList != null) {

			// 遍历文件
			for (com.etc.entity.Files file : fileList) {
				// 复制文件
				copyDocuments.copyDocuments(fromsecondId, tokey, file.getFilename());
			}

		}

		a = 1;
	}
}